package org.nuaa.server;

/* 实现客户端从服务器上下载文件*/

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

import org.nuaa.server.Protocol;

public class Download implements Runnable { //Runnable接口是线程辅助类,可以实现多线程

    Socket socket = null;

    public Download(Socket socket) {
        super(); //来调用父类的无参构造器；
        this.socket = socket;
    }

    public boolean CheckSum(byte[] message) {
        byte check = 0;
        for (int i = 0; i < message.length - 1; i++) {
            check = (byte) ((check + message[i]) % 256);
        }
        if (check == message[message.length - 1]) {
            return true;
        }
        return false;
    }

    public int Sum(char a[]) {
        int sum = 0;
        for (int i = 0; i < a.length; i++)
            sum += a[i];
        return sum - 96;
    }

    public String GetFileAtri(String Filepath) {
        File file = new File(Filepath);
        return "文件名:" + file.getName() + "\n" + "是否可读:" + file.canRead() + "\n" + "是否可写：" + file.canWrite() + "\n" + "文件长度:" + file.length() + "字节" + "\n";
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        try {

            //int times = br.read();//发送tcp报文的次数
            double times = 1e10;//只能传100KB
            System.out.println("times=" + times);

            Scanner reader = new Scanner(System.in);
            String Filepath = reader.next();

            OutputStream os = socket.getOutputStream();

            System.out.println("2");
            String DocumentInf = GetFileAtri(Filepath);
            os.write(DocumentInf.getBytes());
            os.flush();

            DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));//监听客户端是否发送数据
            Integer get = dis.readInt();
            if (get == 0) {
                times = 0;
            }

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os);//发送流
            BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(Filepath));

            byte[] buf = new byte[256];
            int len = 0;
            double i = times;
            int num = 0;
            boolean flag = true;

            while (i > 0) {
                if (flag) { //没出错时
                    len = bufferedInputStream.read(buf);
                    if (len == -1)//-1可能表示读到末尾
                        break;
                }
                Protocol mess = new Protocol(num, buf, len); //protocol表示发送协议，num为第几个文件，buf似乎为读到的数据？
                byte[] message = mess.getContentData(); //得到tcp报文
                bufferedOutputStream.write(message, 0, message.length);
                Thread.sleep(100);
                bufferedOutputStream.flush();
                if (dis.readInt() == 1) {//出错,从输入流中读取4个字节
                    flag = false;
                } else {
                    flag = true;
                    i--;
                }
            }

            bufferedOutputStream.flush();
            socket.shutdownOutput();
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));//BufferedReader类从字符输入流中读取文本并缓冲字符
            String info = null;//info为客户端读到的信息
            while ((info = br.readLine()) != null) {
                System.out.println("客户端信息:" + info);
            }
            socket.shutdownInput();

            os.close();//关闭发送流
            bufferedInputStream.close();//关闭读入缓冲字符流（从文件读入）
            bufferedOutputStream.close();//关闭输出缓冲字符流，传给客户端
            is.close();//关闭读入流(从客户端传来的信息）
            br.close();//关闭读入缓冲字符流(从客户端传来的信息）
            dis.close();//dis为DataInputStream，判断传来信息是否出错
            socket.close();
        } catch (UnknownHostException e) {//当你的IP地址名称找不到对应的ip地址时，触发UnknownHostException
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }


}
